package com.whately.core.base.controller;

import com.whately.core.base.annotation.IgnoreAccessKey;
import com.whately.core.base.constant.ConstantProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  验证access key
 */
public abstract class WhatelyAccessKeyInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(WhatelyAccessKeyInterceptor.class);


    /**
     * 是否包含IgnoreAccessKey
     */
    protected boolean isIgnoreAccessKey(Object handler){
        HandlerMethod method = (HandlerMethod) handler;
        // 方法上注解 ,不是验签，直接跳过
        IgnoreAccessKey ignoreAccessKey = method.getMethodAnnotation(IgnoreAccessKey.class);
        if (null != ignoreAccessKey ) {
            return true;
        }
        return false;
    }

    protected String getRemoteAccessKey(HttpServletRequest httpServletRequest)  {
        String accessKey = httpServletRequest.getHeader(ConstantProject.response_header_access_key);
        return accessKey;
    }

    protected String getRemoteAccessTimestamp(HttpServletRequest httpServletRequest)  {
        String accessTimestamp = httpServletRequest.getHeader(ConstantProject.response_header_access_timestamp);
        return accessTimestamp;
    }

    //解密 throw new ServiceException(ServiceError.ACCESS_KEY_ERROR);
    protected String decodeRemoteKey(String timestamp,String accessKey)   {
        String decodeKey = ClientSignUtil.decodeAk(timestamp,accessKey);
        return decodeKey;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
